package com.n5x.controller.front.user;

import com.n5x.common.base.JsonModel;
import com.n5x.common.base.ResponseCode;
import com.n5x.common.base.TokenModel;
import com.n5x.common.util.StringUtil;
import com.n5x.common.weixinutils.WxPayUtil;
import com.n5x.controller.BaseController;
import com.n5x.model.user.UserInfo;
import com.n5x.model.user.UserTransactionRecord;
import com.n5x.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 前台个人中心接口
 * 需要用户token
 */
@Controller("frontUser")
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    public HttpServletRequest request;

    @Autowired
    private IUserService iUserService;

    @ResponseBody
    @RequestMapping(value = "/getUserInfo")
    public JsonModel info(@RequestParam(value = "token", required = false) String token) {
        try {
            TokenModel tokenModel = getTokenModelByToken(token);
            String userId = tokenModel.getUserId();
            logger.info("[查询用户信息]UserId:{}", new Object[]{userId});
            UserInfo userInfo = iUserService.findUserInfo(userId);
            if (userInfo == null) {
                return getResultError(ResponseCode.Common_DataNotFound, "用户不存在");
            }
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("username", userInfo.getName());
            map.put("balance", userInfo.getBalance());
            map.put("userLevel", userInfo.getFkLevel());
            map.put("address", userInfo.getAddress());
            map.put("recommend", userInfo.getRecommend());
            return getResult(map);
        } catch (Exception e) {
            logger.error("[查询用户信息失败]e:{}", new Object[]{e.toString()});
            e.printStackTrace();
            return getResultError(ResponseCode.Common_Error, e.toString());
        }
    }

    @ResponseBody
    @RequestMapping(value = "/editUserAddress")
    public JsonModel editUserAddress(@RequestParam(value = "token", required = true) String token) {
        try {
            String address = request.getParameter("address");
            if (StringUtil.isBlank(address)) return getResultError(ResponseCode.Common_ParamError, "地址不能为空");
            TokenModel tokenModel = getTokenModelByToken(token);
            String userId = tokenModel.getUserId();
            logger.info("[查询用户信息]UserId:{}", new Object[]{userId});
            UserInfo userInfo = iUserService.findUserInfo(userId);
            if (userInfo == null) {
                return getResultError(ResponseCode.Common_DataNotFound, "用户不存在");
            }
            userInfo.setAddress(address);
            iUserService.saveUserInfo(userInfo);
            return getResult(address);
        } catch (Exception e) {
            logger.error("[查询用户信息失败]e:{}", new Object[]{e.toString()});
            e.printStackTrace();
            return getResultError(ResponseCode.Common_Error, e.toString());
        }
    }


    /**
     * 充值验证
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/transactionRecord/update")
    public JsonModel updateTransactionRecord() {
        try {
            String id = request.getParameter("id");
            UserTransactionRecord userTransactionRecord = iUserService.findUserTransactionRecord(id);
            if (userTransactionRecord == null) {
                return getResultError(ResponseCode.Common_ParamError, "交易记录不存在");
            }
            Thread.sleep(1000);
            Map map = WxPayUtil.queryOrder(userTransactionRecord.getTransactionNumber());
            String tradeState = (String) map.get("tradeState");
            BigDecimal money = new BigDecimal((String) map.get("totalfee"));
            logger.info("[激活充值]id:{},tradeState:{},money:{}", new Object[]{id, tradeState, money});
            if (tradeState.equals(WxPayUtil.PayState.支付成功.getState()) && money.compareTo(userTransactionRecord.getMoney().multiply(new BigDecimal(100))) == 0 && userTransactionRecord.getDisable() == Boolean.TRUE) {
                money = money.divide(new BigDecimal(100));
                UserTransactionRecord extUserTransactionRecord = null;
                String userId = userTransactionRecord.getFkUser();
                if (money.compareTo(new BigDecimal(1000)) == 0) {
                    //充1000送100
                    money = money.add(new BigDecimal(100));
                    extUserTransactionRecord = new UserTransactionRecord(userId, userTransactionRecord.getTransactionNumber(), UserTransactionRecord.Method.微信, UserTransactionRecord.TransactionType.赠送, new BigDecimal(100));
                    extUserTransactionRecord.setDisable(Boolean.FALSE);
                } else if (money.compareTo(new BigDecimal(500)) == 0) {
                    //充500送20
                    money = money.add(new BigDecimal(20));
                    extUserTransactionRecord = new UserTransactionRecord(userId, userTransactionRecord.getTransactionNumber(), UserTransactionRecord.Method.微信, UserTransactionRecord.TransactionType.赠送, new BigDecimal(20));
                    extUserTransactionRecord.setDisable(Boolean.FALSE);
                } else if (money.compareTo(new BigDecimal(300)) == 0) {
                    //充300送5
                    money = money.add(new BigDecimal(5));
                    extUserTransactionRecord = new UserTransactionRecord(userId, userTransactionRecord.getTransactionNumber(), UserTransactionRecord.Method.微信, UserTransactionRecord.TransactionType.赠送, new BigDecimal(5));
                    extUserTransactionRecord.setDisable(Boolean.FALSE);
                }
                userTransactionRecord.setDisable(Boolean.FALSE);
                UserInfo userInfo = iUserService.findUserInfo(userId);
                userInfo.setFkLevel("1");
                userInfo.setBalance(userInfo.getBalance().add(money));
                iUserService.saveUserTransactionRecord(userTransactionRecord, userInfo, extUserTransactionRecord);
                return getResult(userTransactionRecord.getId());
            } else {
                return getResultError(ResponseCode.Common_Fail, "交易失败");
            }
        } catch (Exception e) {
            logger.error("[查询用户信息失败]e:{}", new Object[]{e.toString()});
            e.printStackTrace();
            return getResultError(ResponseCode.Common_Error, e.toString());
        }
    }
}